//
//  WBComposeTypeView.swift
//  仿写微博
//
//  Created by tuimao on 2017/8/8.
//  Copyright © 2017年 tuimao. All rights reserved.
//

import UIKit
import pop
class WBComposeTypeView: UIView {

    //scrollerView
    @IBOutlet weak var scrollerView: UIScrollView!
    //返回按钮
    @IBOutlet weak var returnButton: UIButton!
    //关闭按钮的中心点X约束
    @IBOutlet weak var closeButtonCenterXCons: NSLayoutConstraint!
    //返回按钮的中心点X约束
    @IBOutlet weak var returnButtonCenterXCons: NSLayoutConstraint!
   //完成回调的闭包
    var completionBlock:((_ clsName:String?)->())?
    
    /// 按钮数据数组
    fileprivate let buttonsInfo = [["imageName": "tabbar_compose_idea", "title": "文字", "clsName": "WBComposeViewController"],
                               ["imageName": "tabbar_compose_photo", "title": "照片/视频"],
                               ["imageName": "tabbar_compose_weibo", "title": "长微博"],
                               ["imageName": "tabbar_compose_lbs", "title": "签到"],
                               ["imageName": "tabbar_compose_review", "title": "点评"],
                               ["imageName": "tabbar_compose_more", "title": "更多", "actionName": "clickMore"],
                               ["imageName": "tabbar_compose_friend", "title": "好友圈"],
                               ["imageName": "tabbar_compose_wbcamera", "title": "微博相机"],
                               ["imageName": "tabbar_compose_music", "title": "音乐"],
                               ["imageName": "tabbar_compose_shooting", "title": "拍摄"]]
    
    
    class func ComposeTypeView() ->WBComposeTypeView {
        //nib
        let nib = UINib(nibName: "WBComposeTypeView", bundle: nil)
        //nib创建
        let vc = nib.instantiate(withOwner: nil, options: nil)[0] as! WBComposeTypeView
        //设置nib创建的视图大小
        vc.frame = UIScreen.main.bounds
        //设置UI
        vc.setupUI()
        //返回
        return vc
    }
    
    //展示当前视图
    func show(completion:@escaping (_ clsName:String?)->()){
        //闭包传递点击btn后的clsName
        completionBlock = completion
        //window的根控制器
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else{
            return
        }
        //添加到根视图
        vc.view.addSubview(self)
        //开始动画
        showCurrentView()
    }
    //关闭
    @IBAction func cclose() {
        //关闭动画
        hideButtons()
    }
    //按钮点击事件
    @objc fileprivate func clickButton(clickButton:WBComposeTypeButton){

        // 1. 根据 contentOffset 判断当前显示的子视图
        let page = Int(scrollerView.contentOffset.x / scrollerView.bounds.width)
        let v = scrollerView.subviews[page]
        for (i,btn) in v.subviews.enumerated() {
            //1.缩放动画
            let scaleAnim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            //2 x,y 在系统中使用CGPoint 表示，如果要转换成id，需要使用NSValue包装
            let scale = (clickButton == btn) ? 2 : 0.2
            scaleAnim.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            
            scaleAnim.duration = 0.5
            
            btn.pop_add(scaleAnim, forKey: nil)
            
            //动画组
            let alphaAnim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphaAnim.toValue = 0.2
            alphaAnim.duration = 0.5
            btn.pop_add(alphaAnim, forKey: nil)
            if i == 0 {
                alphaAnim.completionBlock = {(_,_) in
                    //在闭包属性中传递值
                    self.completionBlock?(clickButton.clsName)
                }
            }
        }
    }
    //更多
    @objc fileprivate func clickMore(){
        
        let offset = CGPoint(x: scrollerView.bounds.width, y: 0)
        scrollerView.setContentOffset(offset, animated: true)
        
        let margin = scrollerView.bounds.width / 6
        closeButtonCenterXCons.constant += margin
        returnButtonCenterXCons.constant -= margin
        returnButton.isHidden = false
        UIView.animate(withDuration: 0.25) {
            self.layoutIfNeeded()
        }
    }
    //返回
    @IBAction fileprivate func clickReturn() {
        scrollerView.setContentOffset(CGPoint(x:0,y:0), animated: true)
        closeButtonCenterXCons.constant = 0
        returnButtonCenterXCons.constant = 0
        UIView.animate(withDuration: 0.25, animations: { 
            self.layoutIfNeeded()
            self.returnButton.alpha = 0
        }) { (_) in
            self.returnButton.isHidden = true
            self.returnButton.alpha = 1
        }
    }
}

//MARK:  动画扩展方法
fileprivate extension WBComposeTypeView{
    // MARK: - 消除动画
    /// 隐藏按钮动画
    fileprivate func hideButtons() {
        
        // 1. 根据 contentOffset 判断当前显示的子视图
        let page = Int(scrollerView.contentOffset.x / scrollerView.bounds.width)
        let v = scrollerView.subviews[page]
        
        // 2. 遍历 v 中的所有按钮
        for (i, btn) in v.subviews.enumerated().reversed() {
            
            // 1> 创建动画
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            // 2> 设置动画属性
            anim.fromValue = btn.center.y
            anim.toValue = btn.center.y + 350
            // 设置时间
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count - i) * 0.025
            // 3> 添加动画
            btn.layer.pop_add(anim, forKey: nil)
            
            // 4> 监听第 0 个按钮的动画，是最后一个执行的
            if i == 0 {
                anim.completionBlock = { _, _ in
                    self.hideCurrentView()
                }
            }
        }
    }

    /// 隐藏当前视图
    private func hideCurrentView() {
        
        // 1> 创建动画
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        
        anim.fromValue = 1
        anim.toValue = 0
        anim.duration = 0.25
        
        // 2> 添加到视图
        pop_add(anim, forKey: nil)
        // 3> 添加完成监听方法
        anim.completionBlock = { _, _ in
            self.removeFromSuperview()
        }
    }

    //动画显示当前视图
    func showCurrentView() {
        //创建动画
        let anim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        //动画属性
        anim.fromValue = 0
        anim.toValue = 1
        //时间
        anim.duration = 0.25
        //添加动画
        pop_add(anim, forKey: nil)
        //按钮动画
        showButtons()
    }
    //展示按钮动画
    func showButtons() {
        //把添加在scrollerView上的第一个view取出
        let v = scrollerView.subviews[0]
        for (i,btn) in v.subviews.enumerated() {
            //创建动画
            let anim:POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            //动画属性
            anim.fromValue = btn.center.y + 350
            anim.toValue = btn.center.y
            //动画速度
            anim.springSpeed = 8
            //动画弹力
            anim.springBounciness = 8
            //每个btn动画的时间计算
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            //把动画添加到btn上
            btn.pop_add(anim, forKey: nil)
        }
        
    }
    
}


//MARK:  设置UI
fileprivate extension WBComposeTypeView{
    // 设置UI
    func setupUI(){
        //刷新布局，刚从xib创建的时候，xib里面的视图只是保持自己的size，还没有约束更新
        layoutIfNeeded()
        //设置view的size
        let rect = scrollerView.bounds
        let width = scrollerView.bounds.width
        for i in 0..<2 {
            let v = UIView(frame: CGRect(x: CGFloat(i) * width, y: 0, width: rect.width, height: rect.height))
            
            addButtons(v: v, idx: i * 6)
            //添加到scrollerView
            scrollerView.addSubview(v)
        }
        scrollerView.contentSize = CGSize(width: 2 * width, height: 0)
    }
    // 给view添加button
    func addButtons(v:UIView, idx:Int){
        //
        let count = 6
        //循环创建btn
        for i in idx ..< (idx + count){
            //超出不创建
            if i >= buttonsInfo.count {
                break
            }
            //字典中的索引
            let dic = buttonsInfo[i]
            guard let imageName = dic["imageName"],
                  let title = dic["title"]
                else {
                continue
            }
            //创建btn
           let btn = WBComposeTypeButton.ComposeTypeButton(imageName: imageName, title: title)
            //添加btn
            v.addSubview(btn)
            //更多的点击事件
            // 3> 添加监听方法
            if let actionName = dic["actionName"] {
                // OC 中使用 NSSelectorFromString(@"clickMore")
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            } else {
                btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
            }
            //4 传递按钮的clsName
            btn.clsName = dic["clsName"]
        }
        //循环设置btn的frame
        let size = CGSize(width: 100, height: 100)
        let margin = (v.bounds.width - 3 * size.width) / 4
        for (i,btn) in v.subviews.enumerated() {
            let col = i % 3
            let x = CGFloat(col+1) * margin + CGFloat(col) * size.width
            let y = (i > 2) ? (v.bounds.height - size.height) : 0
            btn.frame = CGRect(x: x, y: y, width: size.width, height: size.height)
            
        }
    }
}


